Custom Blade Directives in Laravel

Laravel allows you to create custom Blade directives, making it easier to reuse and organize common code in your views.


Step 1: Create a Custom Blade Directive

Add custom directives in the boot method of a service provider, such as AppServiceProvider.

use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
    public function boot()
    {
        // add blade directive like this
        Blade::directive('greet', function ($name) {
            return "<?php echo 'Hello, ' . ucfirst($name) . '!'; ?>";
        });
    }
}

Here, @greet('world') will output "Hello, world!" in your view.

Step 2: Use the Custom Directive in Your Blade File

In any Blade file, use the @greet directive:

<!-- welcome.blade.php -->
@php
    $userName = 'john';
@endphp

<p>@greet($userName)</p>

This will render:

<p>Hello, John!</p>

Another Example: Custom Auth Check Directive

Add a custom directive to check if the user is an admin.

Blade::if('admin', function () {
    return auth()->check() && auth()->user()->is_admin;
});

Then, in your Blade file:

@admin
    <p>Welcome, Admin!</p>
@endadmin

This will show the message only if the logged-in user is an admin.

Custom Blade directives make repetitive tasks easier to handle, allowing to create cleaner and more maintainable views.

Use them to simplify your templates!

You Might Also Like

Leverage Chunking for Large Datasets

Process large datasets efficiently by using the chunk method. Chunking retrieves records in smaller...

Composer Packages with Version Constraints

Control which versions of Composer packages should be installed in your project using version constr...